package com.right.health.app.ui.medical;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.magic.basic.activity.BaseActivity;
import com.magic.basic.utils.CollectionUtil;
import com.magic.basic.utils.PermissionUtil;
import com.magic.basic.utils.TimeUtil;
import com.magic.basic.utils.ToastUtil;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.bean.ChooseMemberInfo;
import com.right.health.app.bean.FamilyResponse;
import com.right.health.app.bean.MedicalRecordInfo;
import com.right.health.app.bean.UploadResponse;
import com.right.health.app.common.DataCommon;
import com.right.health.app.constants.BroadCastCode;
import com.right.health.app.constants.BroadCastKey;
import com.right.health.app.db.DaoSharedPreferences;
import com.right.health.app.dialog.BottomPickerDialog;
import com.right.health.app.dialog.DateBottomPickerDialog;
import com.right.health.app.dialog.PhotoDialog;
import com.right.health.app.net.MedicalApi;
import com.right.health.app.net.UploadApi;
import com.right.health.app.ui.me.FamilyActivity;
import com.right.health.app.ui.me.ReviewReminderDetailActivity;
import com.right.health.app.ui.medical.adapter.MedicalRecordAddAdapter;
import com.right.health.app.utils.ChoosePhotoUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
 * Created by hopeliao on 2019-09-29
 * 病历添加
 *
 */
public class MedicalRecordAddActivity extends BaseActivity implements View.OnClickListener, ChoosePhotoUtil.OnChooseImageCallback, OnHttpListener {

    private static final int REQUEST_CODE_FAMILY = 1;

    private static final int HTTP_CODE_UPLOAD_FILE = 1;
    private static final int HTTP_CODE_ADD = 2;
    private static final int HTTP_DETAIL_CODE=3;
    private static final int HTTP_MODIFY_CODE=4;

    private MedicalRecordAddAdapter mAdapter;

    private List<MedicalRecordInfo> mDataSource = new ArrayList<>();

    private BottomPickerDialog<BottomPickerDialog.BottomPickerInfo> mChooseTypeDialog;
    private BottomPickerDialog<BottomPickerDialog.BottomPickerInfo> mCourseDiseaseDialog;

    private DateBottomPickerDialog mDateDialog;

    private PhotoDialog mPhotoDialog;

    private TextView mUserTv, mChooseTimeTv, mChooseTypeTv;

    private ChoosePhotoUtil mChoosePhotoUtil;

    private int mChooseHandlePosition;

    private UploadApi mUploadApi;

    private MedicalApi mMedicalApi;

    private ChooseMemberInfo mCurrMemberInfo;

    private String mChooseType;
    private String mChooseTime;
    private String mTypeName;

    private String mId;//病历id
    private boolean mIsDetail;

    private List<BottomPickerDialog.BottomPickerInfo> mChooseTypeDataSource = new ArrayList<>();
    private List<BottomPickerDialog.BottomPickerInfo> mCourseDiseaseDataSource = new ArrayList<>();
    private String[] mVisitTypes, mDiseaseTypes;

    @Override
    public void onCreate(Bundle bundle, String s) {
        setContentView(R.layout.medical_record_add);
    }

    @Override
    public void findView() {
        mUserTv = (TextView) findViewById(R.id.tv_user);
        mCurrMemberInfo = DaoSharedPreferences.getInstance().getChooseMember();
        if (mCurrMemberInfo != null) {
            mUserTv.setText(mCurrMemberInfo.name);
        }

        findViewById(R.id.tv_save).setOnClickListener(this);
        findViewById(R.id.tv_save).setVisibility(View.VISIBLE);

        mChooseTimeTv = (TextView) findViewById(R.id.tv_choose_time);
        mChooseTypeTv = (TextView) findViewById(R.id.tv_choose_type);
        mChooseTypeTv.setOnClickListener(this);
        mChooseTimeTv.setOnClickListener(this);
        ListView listView = (ListView) findViewById(R.id.listview);
        mAdapter = new MedicalRecordAddAdapter(this);
        mAdapter.setOnClickListener(this);
        mAdapter.setAppendListener(new MedicalRecordAddAdapter.OnAppendPhotListener() {
            @Override
            public void onTap(int pos) {
                mChooseHandlePosition = pos;
                PermissionUtil.with(MedicalRecordAddActivity.this)
                        .listener((succ, requestCode) -> {
                            if (succ) {
                                if (mPhotoDialog == null) {
                                    mPhotoDialog = new PhotoDialog(MedicalRecordAddActivity.this);
                                    mPhotoDialog.setClickListener(MedicalRecordAddActivity.this);
                                }
                                mPhotoDialog.show();
                            }
                        })
                        .request(
                                Manifest.permission.CAMERA);
            }
        });
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startIntent(ReviewReminderDetailActivity.class);
            }
        });
        findViewById(R.id.tv_choose_family).setOnClickListener(this);
        View footView = LayoutInflater.from(this).inflate(R.layout.review_reminder_add_footer, null);
        footView.findViewById(R.id.ib_add).setOnClickListener(this);
        listView.addFooterView(footView);
    }

    @Override
    public void initialize() {
        mUploadApi = new UploadApi();
        mUploadApi.setListener(this);

        mMedicalApi = new MedicalApi();
        mMedicalApi.setListener(this);

        mChoosePhotoUtil = new ChoosePhotoUtil(this);
        mChoosePhotoUtil.setCallback(this);
        mChoosePhotoUtil.setCropParam(1280, 720);

        String[] visitTypes = getResources().getStringArray(R.array.visit_type_arrays);
        for (String str : visitTypes) {
            mChooseTypeDataSource.add(new BottomPickerDialog.BottomPickerInfo(str));
        }

        String[] courseDiseaseArrays = getResources().getStringArray(R.array.course_disease_arrays);
        for (String str : courseDiseaseArrays) {
            mCourseDiseaseDataSource.add(new BottomPickerDialog.BottomPickerInfo(str));
        }
        if (getIntent().getExtras() != null) {
            mIsDetail = getIntent().getBooleanExtra("isDetail", false);
            if (mIsDetail) {
                TextView titleTv = findViewById(R.id.tv_title);
                titleTv.setText("病历详情");
                findViewById(R.id.tv_choose_family).setVisibility(View.GONE);
                mVisitTypes = getResources().getStringArray(R.array.visit_type_arrays);
                mDiseaseTypes = getResources().getStringArray(R.array.course_disease_arrays);
                mChooseTypeTv.setEnabled(false);
                mChooseTimeTv.setEnabled(false);
                mId = getIntent().getExtras().getString("idKey");
                mMedicalApi.addRequestCode(HTTP_DETAIL_CODE);
                mMedicalApi.getMedicalDetil(mId);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_choose_time: //选择就诊时间
//                getDateDialog((int) v.getTag()).show();
                getDateDialog(0).show();
                break;
            case R.id.tv_choose_type: //选择就诊类型
//                int position = (int) v.getTag();
                getChooseTypeDialog(0).show();
                break;
            case R.id.tv_course_disease: //选择病程类型
                getCourseDiseaseDialog((int) v.getTag()).show();
                break;
            case R.id.ib_add: //添加
                if (mAdapter.getDataSource().size() >= 5) {
                    ToastUtil.show(this, "一次性最多添加五条记录");
                    return;
                }
                if (!CollectionUtil.isEmpty(mAdapter.getDataSource())) {
                    mDataSource.clear();
                    for (MedicalRecordInfo info:mAdapter.getDataSource()
                         ) {
                    }
                    mDataSource.addAll(mAdapter.getDataSource());
                }

                mDataSource.add(new MedicalRecordInfo(true));
                mAdapter.mSelectedEditTextPosition =  -1;
                mAdapter.setDataSource(mDataSource);
                break;
            case R.id.tv_choose_family: //切换人员
                FamilyActivity.makeActivity(this, true, REQUEST_CODE_FAMILY);
                break;
            case R.id.tv_choose_camera://相机
                mChoosePhotoUtil.choosePhoto();
                dismissPhotoDialog();
                break;
            case R.id.tv_choose_album: //相册
                mChoosePhotoUtil.chooseAlbum();
                dismissPhotoDialog();
                break;
            case R.id.tv_del: //删除
                final int pos = (int) v.getTag();
                final AlertDialog dialog = DataCommon.getDeleteDialog(this, (dialog1, which) -> {
                    dialog1.dismiss();
                    mDataSource.remove(pos);
                    mAdapter.setDataSource(mDataSource);
                });
                dialog.show();
                break;
            case R.id.tv_save: //保存
                if (mIsDetail) {
                 modify();
                }else {
                    send2Net();
                }
                break;
        }
    }

    private void send2Net() {
        mDataSource.clear();
        mDataSource.addAll(mAdapter.getDataSource());
        if (CollectionUtil.isEmpty(mDataSource)) {
            ToastUtil.show(this, "请先添加您的病历记录");
            return;
        }
        if (mCurrMemberInfo == null) {
            ToastUtil.show(this, "请选择人员");
            return;
        }
        if (TextUtils.isEmpty(mChooseType) || TextUtils.isEmpty(mTypeName)) {
            ToastUtil.show(this, "请选择就诊类型");
            return;
        }
        if (TextUtils.isEmpty(mChooseTime)) {
            ToastUtil.show(this, "请选择就诊时间");
            return;
        }
        for (MedicalRecordInfo info : mDataSource) {


            if (TextUtils.isEmpty(info.infectionprogresstype) || TextUtils.isEmpty(info.infectionprogressName)) {
                ToastUtil.show(this, "请选择病程类型");
                return;
            }
            if (TextUtils.isEmpty(info.casehistorydesc)) {
                ToastUtil.show(this, "请输入相关描述");
                return;
            }
            if (TextUtils.equals(info.photoDataSource.get(0),"add")) {
                ToastUtil.show(this, "请上传您的病例图片");
                return;
            }
        }

        mMedicalApi.addRequestCode(HTTP_CODE_ADD);
        mMedicalApi.addMedicals(mCurrMemberInfo.id, getResources().getString(R.string.def_hospital_code), mChooseTime,mChooseType,mDataSource);

    }

    private void modify(){
        mDataSource.clear();
        mDataSource.addAll(mAdapter.getDataSource());
        for (MedicalRecordInfo info : mDataSource) {


            if (TextUtils.isEmpty(info.infectionprogresstype) || TextUtils.isEmpty(info.infectionprogressName)) {
                ToastUtil.show(this, "请选择病程类型");
                return;
            }
            if (TextUtils.isEmpty(info.casehistorydesc)) {
                ToastUtil.show(this, "请输入相关描述");
                return;
            }
            if (TextUtils.equals(info.photoDataSource.get(0),"add")) {
                ToastUtil.show(this, "请上传您的病例图片");
                return;
            }
        }
        mMedicalApi.addRequestCode(HTTP_MODIFY_CODE);
        mMedicalApi.modifyMedicals(mId,mDataSource);
    }

    private void dismissPhotoDialog() {
        if (mPhotoDialog != null && mPhotoDialog.isShowing()) {
            mPhotoDialog.dismiss();
        }
    }

    private void dismissCourseDiseaseDialog() {
        if (mCourseDiseaseDialog != null && mCourseDiseaseDialog.isShowing()) {
            mCourseDiseaseDialog.dismiss();
        }
    }

    private BottomPickerDialog getCourseDiseaseDialog(int tag) {
        if (mCourseDiseaseDialog == null) {
            mCourseDiseaseDialog = new BottomPickerDialog<>(this);
            mCourseDiseaseDialog.setChooseListener((tag1, num) -> {
                int position = (int) tag1;
                dismissCourseDiseaseDialog();
                mDataSource.clear();
                mDataSource.addAll(mAdapter.getDataSource());

                BottomPickerDialog.BottomPickerInfo bottomPickerInfo = mCourseDiseaseDataSource.get(num);

                MedicalRecordInfo info = mDataSource.get(position);
                info.infectionprogressName = bottomPickerInfo.getName();
                info.infectionprogresstype = String.valueOf(num);

                mDataSource.set(position, info);
                mAdapter.setDataSource(mDataSource);
            });
            mCourseDiseaseDialog.setDataSource(mCourseDiseaseDataSource);
        }
        mCourseDiseaseDialog.setTag(tag);
        return mCourseDiseaseDialog;
    }

    private void dismissDateDialog() {
        if (mDateDialog != null && mDateDialog.isShowing()) {
            mDateDialog.dismiss();
        }
    }

    private DateBottomPickerDialog getDateDialog(int tag) {
        if (mDateDialog == null) {
            mDateDialog = new DateBottomPickerDialog(this);
            mDateDialog.setDelegate((tag1, year, month, date) -> {
                dismissDateDialog();
                mChooseTime = year + "-" + month + "-" + date;
                mChooseTimeTv.setText(mChooseTime);

            });
        }
        mDateDialog.setTag(tag);
        return mDateDialog;
    }

    private String getVisitTypeName(String indexStr) {
        String typeName = "";
        try {
            int index = Integer.parseInt(indexStr);
            typeName = mVisitTypes[index];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return typeName;
    }

    private String getDiseaseTypeName(String indexStr) {
        String typeName = "";
        try {
            int index = Integer.parseInt(indexStr);
            typeName = mDiseaseTypes[index];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return typeName;
    }

    private void dismissChooseTypeDialog() {
        if (mChooseTypeDialog != null && mChooseTypeDialog.isShowing()) {
            mChooseTypeDialog.dismiss();
        }
    }

    private BottomPickerDialog getChooseTypeDialog(int tag) {
        if (mChooseTypeDialog == null) {
            mChooseTypeDialog = new BottomPickerDialog<>(this);
            mChooseTypeDialog.setChooseListener((tag1, num) -> {
                dismissChooseTypeDialog();

                BottomPickerDialog.BottomPickerInfo bottomPickerInfo = mChooseTypeDataSource.get(num);

                mTypeName = bottomPickerInfo.getName();
                mChooseType = String.valueOf(num);
                mChooseTypeTv.setText(mTypeName);
            });
            mChooseTypeDialog.setDataSource(mChooseTypeDataSource);
        }
        mChooseTypeDialog.setTag(tag);
        return mChooseTypeDialog;
    }

    private void refreshUI() {
        mChooseTime = TimeUtil.convertTime("yyyy-MM-dd", mDataSource.get(0).casehistorytime);
        mChooseType = mDataSource.get(0).visittype;
        mChooseTypeTv.setText(mDataSource.get(0).visitName);
        mChooseTimeTv.setText(mChooseTime);
        mChooseTimeTv.setCompoundDrawables(null,null,null,null);
        mAdapter.setDataSource(mDataSource);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_FAMILY) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    FamilyResponse.FamilyInfo familyInfo = bundle.getParcelable(BroadCastKey.DATA);
                    if (familyInfo != null && mCurrMemberInfo != null) {
                        mUserTv.setText(familyInfo.membername);
                        mCurrMemberInfo.id = familyInfo.memberid;
                    }
                }
            } else {
                mChoosePhotoUtil.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissChooseTypeDialog();
        dismissDateDialog();
        dismissPhotoDialog();
    }


    @Override
    public void onResult(String filePath) {
        mUploadApi.addRequestCode(HTTP_CODE_UPLOAD_FILE);
        mUploadApi.uploadFile(filePath);

        ToastUtil.show(this, "图片上传中,请稍等");
    }

    @Override
    public void onResponse(Request request, Response response) {
        if (response.isResponseFail()) {
            ToastUtil.show(this, response.error);
        } else {
            if (request.requestCode == HTTP_CODE_UPLOAD_FILE) {
                if (response.targetData instanceof UploadResponse) {
                    UploadResponse uploadResponse = response.cast(UploadResponse.class);
                    if (CollectionUtil.isEmpty(uploadResponse.imgPath)) {
                        return;
                    }
                    String imageServerPath = uploadResponse.imgPath.get(0);
                    List<MedicalRecordInfo> dataSource = mAdapter.getDataSource();
                    if (mChooseHandlePosition >= 0 && mChooseHandlePosition < dataSource.size()) {
                        MedicalRecordInfo info = dataSource.get(mChooseHandlePosition);
                        info.photoDataSource.remove(0);
                        info.photoDataSource.add(0, imageServerPath);
                        dataSource.set(mChooseHandlePosition, info);

                        mDataSource.clear();
                        mDataSource.addAll(dataSource);
                        mAdapter.setDataSource(mDataSource);
                    }
                }
            } else if (request.requestCode == HTTP_CODE_ADD) {
                ToastUtil.show(this, R.string.add_succ);
                sendBroadcast(BroadCastCode.REFRESH_MEDICAL);
                finish();
            } else if (request.requestCode == HTTP_MODIFY_CODE) {
                ToastUtil.show(this, "修改成功");
            } else if (request.requestCode == HTTP_DETAIL_CODE) {
                if (!TextUtils.isEmpty(response.data)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.data);
                        mDataSource = new Gson().fromJson(jsonObject.getString("casehistory"), new TypeToken<List<MedicalRecordInfo>>() {
                        }.getType());
                        if (!CollectionUtil.isEmpty(mDataSource)) {
                            for (MedicalRecordInfo info : mDataSource) {
                                info.infectionprogressName = getDiseaseTypeName(info.infectionprogresstype);
                                info.visitName = getVisitTypeName(info.visittype);
                                if (!TextUtils.isEmpty(info.casehistorypics)) {
                                    String[] pics = info.casehistorypics.split(",");
                                    info.photoDataSource = Arrays.asList(pics);
                                }
                                if (CollectionUtil.isEmpty(info.photoDataSource)) {
                                    info.initPhotoList();
                                }
                            }
                            refreshUI();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("TAG", "onResponse: " + e.getMessage());
                        com.vendor.social.utils.ToastUtil.show(this, "数据异常");
                    }

                } else {
                    com.vendor.social.utils.ToastUtil.show(this, "数据异常");
                }
            }
        }
    }
}
